/**
 * @desc: 新增/编辑收件地址信息面板弹框
 * @item {object} 需要用来回显的数据
 * @title {string} 标题
 * @visible { bool} 
 * @handleOK { func} 点击保存后的回调
 * @handleCancel {func} 点击取消弹框事件
 * @isSave {bool} 是否需要保存地址到用户表中
 */
import React, { useState, useEffect } from 'react';
import { Form, Input, Cascader, Button } from 'antd';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import { layout1 } from '@/utils/config';
import { getAllArea } from '@/services/common';

const { TextArea } = Input

export default ({ item={}, title, visible, handleOk, handleCancel, isSave=true }) => {
 
  const [form] = Form.useForm();
  const [ data, setData ] = useState([]);
  const [ loading, setLoading ] = useState(false);

  const [ receiveObj, setObj ] = useState({});

  useEffect(() => {
    getAreaList();
  }, [])

  useEffect(() => {
    if(visible) {
      form.resetFields();
    }
  }, [ visible ])

  const getAreaList = async () => {
    const res = await getAllArea();
    if(res.success) {
      setData(res.data);
    }
  }

  const onOk = () => {
    form.validateFields().then(val => {
      if(isSave) {
        handleSaveData(val)
      } else {
        handleOk({ ...item, ...val, ...receiveObj });
      }
    }).catch(err => {

    })
  }

  const handleSaveData = async val => {
    setLoading(true);
    //调用保存接口
    const res = await getAreaList();
    if(res.success) {
      message.success('保存成功！');
      handleOk({ ...item, ...val, ...receiveObj });
    }
    setLoading(false);
  }

  const handleFormatData = () => {
    const val = form.getFieldValue('message');
    if (val) {
      try {
        const result = AddressParse.parse(val.replace(/\s+/g,''))[0];
        let provinceId,cityId,areaId;
        if(result.province && result.city && result.area) {
          const proObj = find(data, ['name', result.province.replace('省', '')]);
          provinceId = proObj.id;
          const cityObj = find(proObj.childs, ['name', result.city]);
          cityId = cityObj.id;
          const areaObj = find(cityObj.childs, ['name', result.area])
          areaId = areaObj.id;
          const obj2 = {};
          obj2.receiverProvince = result.province;
          obj2.receiverCity = result.city;
          obj2.receiverDistrict = result.area;
          setObj(obj2);
        }
        form.setFieldsValue({
          receiverName: result.name,
          receiverMobile: result.mobile,
          receiverAddress: result.details.length > 120 ? result.details.slice(0, 120) : result.details,
          address: provinceId ? [provinceId, cityId, areaId] : undefined,
        })
      } catch (error) {
        console.log(error);
        message.error('地址识别失败');
      }
    } else {
        message.warning('请输入识别内容！')
    }
  }

  const onChange = (val, option) => {
    const obj = {};
    obj.receiverProvince = option[0].name;
    obj.receiverCity = option[1].name;
    obj.receiverDistrict = option[2].name;
    obj.receiverDistrictId = val[2];
    setObj(obj);
  }

  return (
    <CommonModal
      title={title}
      visible={visible}
      onOk={onOk}
      onCancel={handleCancel}
      width='600px'
    >
        <Form { ...layout1 } form={form} initialValues={{ ...item }} name="add-recipient">
          <Form.Item name="message" label="地址识别" extra='复制第三方订单详情页的收货地址，然后点击右侧的“一键识别” 如：【李**，13658626452，广东省 广州市 天河区 *********，000022】'>
            <div style={{ display: 'flex' }}>
              <TextArea rows={3}/>
              <Button onClick={handleFormatData} style={{ marginLeft: '12px' }}>一键识别</Button>
            </div>
          </Form.Item>
          <Form.Item name="receiverName" label="收件人" rules={
            [
              { required: true, message: '收件人不能为空' }
            ]
          }>
            <Input placeholder="最多30个字符" maxLength="30" />
          </Form.Item>
          <Form.Item name="receiverMobile" label="联系电话" rules={
            [
              { required: true, message: '联系方式必填' }
            ]
          }>
            <Input placeholder="请填写联系方式，格式:18888888888或0571-88888888" />
          </Form.Item>
          <Form.Item name="address" label="所在地区" rules={
            [
              { required: true, message: '地区未选择' }
            ]
          }>
            <Cascader options={data} onChange={onChange} fieldNames={{ label: 'name', value: 'id', children: 'childs' }} placeholder="请选择地区" />
          </Form.Item>
          <Form.Item name="receiverAddress" label="详细地址" rules={
            [
              { required: true, message: '详细地址未填写',}
            ]
          }>
            <TextArea rows={3} maxLength="120" placeholder="最多120个字符" />
          </Form.Item>
          {
            !isSave &&
            <Form.Item name="orderRemark" label="订单备注" rules={
              [
                { required: true, message: '详细地址未填写',}
              ]
            }>
              <TextArea rows={2} maxLength="100" placeholder="最多100个字符" />
            </Form.Item>
          }
          
        </Form>
        <CommonLoading loading={loading} />
    </CommonModal>
  )
}